package com.demo3;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-12-22
 * Time: 15:08
 */
class MyThreadPool{
    //先描述任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    //描述一个工作线程 就是从任务队列取数据
    static class Worker extends Thread{

        //为了拿到上面的任务 写一个构造方法获取到
        private BlockingQueue<Runnable> queue = null;

        public Worker(BlockingQueue<Runnable> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            //拿到上面的任务队列中的任务
            while(true){
                //循环的获取任务
                try {
                    Runnable runnable = queue.take();
                    //获取之后 执行
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //4.创建数据结构来组织若干线程
    private List<Thread> workers = new ArrayList<>();

    public MyThreadPool(int n){
        //在构造方法中创建若干线程 放到上诉队列中
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker(queue);
            worker.start();
            workers.add(worker);
        }
    }

    //创建一个方法 程序员可以放任务到线程池中
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


//线程池
public class Pool {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("哈哈");
                }
            });
        }
    }
}
